package top.cardone.validator.func;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.GenericValidator;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/19.
 */
@Log4j2
public class RangeLengthValidatorFunc extends RequiredValidatorFunc {
	public RangeLengthValidatorFunc() {
		this.code = "validator.rangelength";
	}

	@Override
	public String func(Map<String, Object> map, String key, Object rule, Object message) {
		log.debug(this.code + ":" + key);

		String val = MapUtils.getString(map, key);

		if (StringUtils.isBlank(val)) {
			return null;
		}

		if (rule == null) {
			return null;
		}

		if (!(rule instanceof List)) {
			return null;
		}

		List<Double> range = (List<Double>) rule;

		if (GenericValidator.isInRange(StringUtils.length(val), range.get(0), range.get(1))) {
			return null;
		}

		return this.getMessage(message, ArrayUtils.toArray(range));
	}
}